package toXML;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;

import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import javax.xml.transform.stream.StreamResult;

import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;

public class DataToXML {
	static TransformerHandler hd;
	static PrintWriter out;

	public static void init(File f) throws TransformerConfigurationException,
			FileNotFoundException, SAXException {

		PrintWriter out = new PrintWriter(f);
		StreamResult streamResult = new StreamResult(out);
		SAXTransformerFactory tf = (SAXTransformerFactory) SAXTransformerFactory
				.newInstance();
		hd = tf.newTransformerHandler();
		Transformer serializer = hd.getTransformer();
		serializer.setOutputProperty(OutputKeys.ENCODING, "ISO-8859-1");
		serializer.setOutputProperty(OutputKeys.INDENT, "yes");
		hd.setResult(streamResult);
		hd.startDocument();
		atts = new AttributesImpl();
	}

	public static String sensorData = "sensorData";
	public static String entryTime = "scenarioEntry";
	public static String sensorid = "sensorId";
	public static String type = "type";
	public static String zoneId = "zoneId";
	static AttributesImpl atts;

	public static void save(String psensor_id, String ptype, String proom_id,
			String pvalue) throws FileNotFoundException,
			TransformerConfigurationException, SAXException {
		atts.clear();
		atts.addAttribute("", "", sensorid, "CDATA", psensor_id);
		atts.addAttribute("", "", type, "CDATA", ptype);
		atts.addAttribute("", "", zoneId, "CDATA", proom_id);
		hd.startElement("", "", sensorData, atts);
		hd.characters(pvalue.toCharArray(), 0, pvalue.toCharArray().length);
		hd.endElement("", "", sensorData);

	}

	public static void newEntry(String time) throws SAXException {
		atts.clear();
		atts.addAttribute("", "", "time", "CDATA", time);
		hd.startElement("", "", entryTime, atts);
	}

	public static void closeEntry() throws SAXException {
		hd.endElement("", "", entryTime);
	}

	public static void closeDocument() {
		try {
			hd.endDocument();
		} catch (SAXException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
}
